package com.control;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Observable;

import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.model.Node;
import com.model.Tree;
import com.view.MyJTree;
import com.view.optionpanel.ShowMessage;

public class TreeItemControl extends Observable implements
		TreeSelectionListener {

	protected JTree jtree;
	protected JPanel jPanel;
	public MyTreeControl<String> ItemTree;

	public TreeItemControl() {
		jPanel = new JPanel();
		ItemTree = new MyTreeControl<>(JSONObject.parseObject(
				TreeIOControl.getTreeIO(), Tree.class));// 获取最新目录
		jtree = new MyJTree(ItemTree);
		jPanel.add(jtree);
		jtree.addTreeSelectionListener(this);
	}

	public JPanel TreePanel() {// 获取目录面板
		return this.jPanel;
	}

	public Boolean CheckFloder(String path) {// 判断文件是否为文件夹
		//System.out.println(path);
		Node<String> ns = ItemTree.getNode(ItemTree.getIdByPath(path));
		//System.out.println("duqumingzi"+ns.getData().toString());
		if (ns.getType() == 0)
			return true;
		else
			return false;
	}
	
	public boolean setStartNum(String nodepath,int start){
		int id = this.ItemTree.getIdByPath(nodepath);
		Node<String> myself = this.ItemTree.getNode(id);
		myself.setStart(start);
		String newTree = getTreeJSon(this.ItemTree);
		TreeIOControl.setTreeIO(newTree);
		return true;
	}

	public boolean AddTreeFile(String path, String name) {// 新建文件
		//System.out.println(path);
		int fatherid = ItemTree.getIdByPath(path);
		Node<String> father = this.ItemTree.getNode(fatherid);
		Node<String> b = new Node<String>(name);
		if (this.ItemTree.add(b, father, 1)) {
			String newTree = getTreeJSon(this.ItemTree);
			TreeIOControl.setTreeIO(newTree);
			return true;
		}else{
			return false;
		}
	}
	
	public boolean ExitPath(String path) {
		System.out.println(path);
		int id = ItemTree.getIdByPath(path);
		System.out.println(id);
		if(id==0){
			return false;
		}
		else {
			return true;
		}
	}

	public boolean AddTreeFolder(String path, String name) {// 新建目录
		//System.out.println(path);
		int fatherid = ItemTree.getIdByPath(path);
		Node<String> father = this.ItemTree.getNode(fatherid);
		Node<String> b = new Node<String>(name);
		if (this.ItemTree.add(b, father, 0)) {
			String newTree = getTreeJSon(this.ItemTree);
			TreeIOControl.setTreeIO(newTree);
			return true;
		}else{
			return false;
		}
	}

	public boolean DeleteTree(String path) {// 删除节点
		int nodeid = this.ItemTree.getIdByPath(path);
		System.out.println("错误id"+nodeid);
		if (this.ItemTree.getNode(nodeid).getChildNodes().size() == 0) {
			
			if(this.ItemTree.getNode(nodeid).getStart()!=0){
				
				FileReader fr=null;
				try{
				fr=new FileReader("resources/test2.txt");
				}catch(Exception e){
					System.out.println("第一个catch");
				}
		        BufferedReader br=new BufferedReader(fr);
		        String line="";
		        int i=0;
		        int a[]=new int[128];
		        try {
					while ((line=br.readLine())!=null) {
						int d = Integer.parseInt(line);
						a[i]=d;a[0]=-1;
						System.out.println(a[i]);
						i++;
//		            System.out.println(d);
					}
				} catch (NumberFormatException e) {
					System.out.println("第2个catch");
				} catch (IOException e) {
					System.out.println("第3个catch");
				}
		        try {
					br.close();
					fr.close();
				} catch (IOException e) {
					System.out.println("第4个catch");
				}
		        
		        int start=this.ItemTree.getNode(nodeid).getStart();
		        System.out.println(start);
		        if(start>0){
		        	int b=start;
		        	while(b!=-1){
		        		int c=a[b];
		        		if(a[b]==-1){
		        			a[b]=0;
		        			break;
		        		}
		        		else{
		        		a[b]=0;
		        		b=c;
		        		System.out.println(b);
		        		}
		        	}
		        }
		        
		        File q = new File("resources/test2.txt");
				Writer rdf = null;
					try {
						rdf = new FileWriter(q);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
//					rdf.write("-1\n");
					try {
						rdf.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		        
		        FileWriter fileWriter = null;
				try {
					fileWriter = new FileWriter("resources/test2.txt",true);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				for (int f = 0; f < a.length; f++) {
				try {
					fileWriter.write(String.valueOf(a[f])+"\n");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				}
				try {
					fileWriter.flush();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				try {
					fileWriter.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
			
			this.ItemTree.killChild(nodeid);
			this.ItemTree.removeNode(nodeid);
			String newTree = getTreeJSon(this.ItemTree);
			TreeIOControl.setTreeIO(newTree);
			return true;
		} else {
			ShowMessage.error("目录不为空！", null);
			return false;
		}
		
	}
	

	public String getTreeJSon(MyTreeControl<String> mytree) {
		return JSON.toJSONString(mytree.getTree());

	}

	@SuppressWarnings("unchecked")
	@Override
	public void valueChanged(TreeSelectionEvent e) {// 监听JTree目录
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) jtree
				.getLastSelectedPathComponent();
		TreeNode tr[] = node.getPath();
		this.jtree.setExpandsSelectedPaths(true);
		@SuppressWarnings("rawtypes")
		List<TreeNode> list = new ArrayList(Arrays.asList(tr));
		String path = "";
		for (TreeNode t : list) {
			path = path + t.toString() + "\\";
		}
		path = path.substring(0, path.length() - 1);
		super.setChanged();// 改变属性值
		this.notifyObservers(path);// 告诉观测者，自己发生变化
	}

}
